package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.commons.WemediaConstants;
import com.heima.common.commons.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    WmNewsAutoScanService wmNewsAutoScanService;
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查是否有分页数据
        dto.checkParam();
        //分页查询器的创建
        IPage page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //判断状态
        if (dto.getStatus() != null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //频道查询
        if (dto.getChannelId()!=null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //时间范围查询
        if (dto.getBeginPubDate()!=null &&dto.getEndPubDate()!=null){
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //关键字模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())){
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //获取当前用户的信息
        WmUser user = WmThreadLocalUtil.getUser();
        lambdaQueryWrapper.eq(WmNews::getUserId,user.getApUserId());
        //发布时间倒序查询
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);
        IPage resultpage = page(page, lambdaQueryWrapper);
        //返回结果
        PageResponseResult pageResponseResult =
                new PageResponseResult(dto.getPage(), dto.getSize(), (int) resultpage.getTotal());
        pageResponseResult.setData(resultpage.getRecords());
        return pageResponseResult;
    }
    @Autowired
    WmNewsTaskService wmNewsTaskService;
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //无限参数拦截
        if (dto == null && dto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存或者修改文章
       // 1.先提取部分字段到wmnews中
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //封面图片list ->string
        if (dto.getImages()!=null &&dto.getImages().size()>0){
            String imagestr = StringUtil.join(dto.getImages(),",");
            wmNews.setImages(imagestr);
        }
        //判断当前封面的类型是否为-1
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        saveOrUpdateWmNews(wmNews);
        //判断是否为草稿，是草稿就结束
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //不是草稿，保存文章内容图片与素材的关系
         //获取文章内容中的图片
        List<String> materials = ectracUrlInfo(dto.getContent());
        saveRelativeinfoForcontent(materials,wmNews.getId());
        //判断封面是否设置的有照片，以及保存封面照片和素材之间的关系
        saveRelativeInforForCover(dto,wmNews,materials);
        try {
            Thread.sleep(1800);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime() );
        return new ResponseResult<>().ok(AppHttpCodeEnum.SUCCESS);
    }
    /**
     * 文章的上下架
     * @param dto
     * @return
     */
    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if (ObjectUtils.isEmpty(dto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmnews = getById(dto.getId());
        if(wmnews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否已发布
        if (!wmnews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章enable
        if (dto.getEnable()!=null&&dto.getEnable()>-1&&dto.getEnable()<2){
            update(Wrappers.<WmNews>lambdaUpdate().
                    set(WmNews::getEnable,dto.getEnable()).
                    eq(WmNews::getId,wmnews.getId()));
        }
        if (wmnews.getArticleId()!=null){
            HashMap<String, Object> map = new HashMap<>();
            map.put("articleId",wmnews.getArticleId());
            map.put("enable",dto.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInforForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();
        //如果当前封面类型选择的是自动，则设置封面类型的数据
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            //多图
            if (materials.size()>=3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images =materials.stream().limit(3).collect(Collectors.toList());
            }else if (materials.size()>=1 && materials.size()<3){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            }else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            //修改文章
            if (images!=null && images.size()>0){
                wmNews.setImages(StringUtil.join(images,","));
            }
            updateById(wmNews);
        }
        if (images != null && images.size()>0){
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    /**
     * 保存news到表中，无论还是草稿还是真的都要保存
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtil.getUser().getApUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short)1);//默认上架
        //判断是不是更新操作,不是就更新
        if (wmNews.getId()==null){
            save(wmNews);
        }else {
            //此处为更新操作,先删除原来存在数据库的就消息
            wmNewsMaterialMapper
                    .delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }
    }

    /**
     * 处理文章中的图片和素材的关系
     * @param materials
     * @param newsid
     */

    private void saveRelativeinfoForcontent(List<String> materials, Integer newsid) {
        saveRelativeInfo(materials,newsid, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存文章图片与素材多对多的关系到表中
     * @param materials
     * @param newsid
     * @param wmContentReference
     */
    @Autowired
    WmMaterialMapper wmMaterialMapper;

    private void saveRelativeInfo(List<String> materials, Integer newsid, Short wmContentReference) {
        if (materials!=null && !materials.isEmpty()){
            //通过图片的url查询素材的id
            List<WmMaterial> dbMaterials = wmMaterialMapper.
                    selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
            //判断查询到的素材是否有效
            if (materials==null&&materials.size()==0){
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE);
            }
            if (materials.size()!=dbMaterials.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE);
            }
            List<Integer> idlist =
                    dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //批量保存
            wmNewsMaterialMapper.saveRelations(idlist,newsid,wmContentReference);
        }

    }

    private List<String> ectracUrlInfo(String content) {
        ArrayList<String> materials = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")){
                String imagurl = (String)map.get("value");
                materials.add(imagurl);
            }
        }
    return materials;
    }
}
